import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

/// 列表数据管理抽象基类
/// 用于统一管理列表的加载状态、数据等
abstract class BaseListController<T> {
  /// 列表数据
  final List<T> items = [];

  /// 刷新控制器
  final RefreshController refreshController = RefreshController();

  /// 是否正在加载中
  bool isLoading = false;

  /// 是否有更多数据
  bool hasMore = true;

  /// 当前页码
  int currentPage = 1;

  /// 每页数据数量
  int pageSize = 20;

  /// 初始化数据
  Future<void> initData() async {
    try {
      isLoading = true;
      currentPage = 1;
      final List<T> data = await loadData(page: currentPage, pageSize: pageSize);
      items.clear();
      items.addAll(data);
      hasMore = data.length == pageSize;
    } catch (e) {
      print('Init data error: $e');
    } finally {
      isLoading = false;
      refreshController.refreshCompleted();
    }
  }

  /// 刷新数据
  Future<void> refreshData() async {
    try {
      currentPage = 1;
      final List<T> data = await loadData(page: currentPage, pageSize: pageSize);
      items.clear();
      items.addAll(data);
      hasMore = data.length == pageSize;
    } catch (e) {
      print('Refresh data error: $e');
    } finally {
      refreshController.refreshCompleted();
    }
  }

  /// 加载更多数据
  Future<void> loadMoreData() async {
    if (!hasMore || isLoading) {
      refreshController.loadComplete();
      return;
    }

    try {
      isLoading = true;
      currentPage++;
      final List<T> data = await loadData(page: currentPage, pageSize: pageSize);
      if (data.isNotEmpty) {
        items.addAll(data);
        hasMore = data.length == pageSize;
      } else {
        hasMore = false;
      }
    } catch (e) {
      print('Load more data error: $e');
      currentPage--;
      refreshController.loadFailed();
    } finally {
      isLoading = false;
      refreshController.loadComplete();
    }
  }

  /// 加载数据的抽象方法，需要子类实现
  Future<List<T>> loadData({required int page, required int pageSize});

  /// 清理资源
  void dispose() {
    refreshController.dispose();
  }
}